package com.ruoyi.project.mobile.jiaqin;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.R;
import com.ruoyi.common.utils.RFactory;
import com.ruoyi.project.jiaqin.apply.domain.CompanyApply;
import com.ruoyi.project.jiaqin.apply.service.ICompanyApplyService;
import com.ruoyi.project.jiaqin.company.domain.Company;
import com.ruoyi.project.jiaqin.company.service.ICompanyService;
import com.ruoyi.project.jiaqin.companyindustry.domain.CompanyIndustry;
import com.ruoyi.project.jiaqin.companyindustry.service.ICompanyIndustryService;
import com.ruoyi.project.jiaqin.companymsg.domain.CompanyMsg;
import com.ruoyi.project.jiaqin.companymsg.service.ICompanyMsgService;
import com.ruoyi.project.jiaqin.companyproduct.domain.CompanyProduct;
import com.ruoyi.project.jiaqin.companyproduct.service.ICompanyProductService;
import com.ruoyi.project.jiaqin.cooperatemsg.domain.CooperateMsg;
import com.ruoyi.project.jiaqin.cooperatemsg.service.ICooperateMsgService;
import com.ruoyi.project.jiaqin.followcompany.domain.JiaqinFollowCompany;
import com.ruoyi.project.jiaqin.followcompany.service.IJiaqinFollowCompanyService;
import com.ruoyi.project.jiaqin.followmember.domain.JiaqinFollowMember;
import com.ruoyi.project.jiaqin.followmember.service.IJiaqinFollowMemberService;
import com.ruoyi.project.jiaqin.intentionmessage.domain.IntentionMessage;
import com.ruoyi.project.jiaqin.intentionmessage.service.IIntentionMessageService;
import com.ruoyi.project.jiaqin.mcooperate.domain.Cooperate;
import com.ruoyi.project.jiaqin.mcooperate.service.ICooperateService;
import com.ruoyi.project.jiaqin.memberquotationclass.domain.MemberQuoteClass;
import com.ruoyi.project.jiaqin.memberquotationclass.service.IMemberQuoteClassService;
import com.ruoyi.project.jiaqin.numbertips.domain.NumberTips;
import com.ruoyi.project.jiaqin.numbertips.service.INumberTipsService;
import com.ruoyi.project.jiaqin.recruitindustry.domain.RecruitIndustry;
import com.ruoyi.project.jiaqin.recruitindustry.service.IRecruitIndustryService;
import com.ruoyi.project.jiaqin.supplycollect.domain.JiaqinSupplyCollect;
import com.ruoyi.project.jiaqin.supplycollect.service.IJiaqinSupplyCollectService;
import com.ruoyi.project.jiaqin.viprecord.domain.JiaqinBuyvipRecord;
import com.ruoyi.project.jiaqin.viprecord.service.IJiaqinBuyvipRecordService;
import com.ruoyi.project.mobile.utils.PayUtil;
import com.ruoyi.project.mobile.utils.WxPayConfigRuImpl;
import com.ruoyi.project.system.member.domain.Member;
import com.ruoyi.project.system.member.enums.MemberIsVip;
import com.ruoyi.project.system.member.service.IMemberService;
import com.ruoyi.project.system.shopconfig.domain.ShopConfig;
import com.ruoyi.project.system.shopconfig.service.IShopConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/jq/user")
public class ApiJqUserController {

    @Autowired
    private ICompanyApplyService iCompanyApplyService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IJiaqinBuyvipRecordService iJiaqinBuyvipRecordService;
    @Autowired
    private IJiaqinFollowCompanyService iJiaqinFollowCompanyService;
    @Autowired
    private IJiaqinFollowMemberService iJiaqinFollowMemberService;
    @Autowired
    private IIntentionMessageService intentionMessageService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private IJiaqinSupplyCollectService iJiaqinSupplyCollectService;
    @Autowired
    private ICompanyService iCompanyService;
    @Autowired
    private IRecruitIndustryService iRecruitIndustryService;
    @Autowired
    private IMemberQuoteClassService iMemberQuoteClassService;
    @Autowired
    private ICompanyIndustryService iCompanyIndustryService;
    @Autowired
    private ICompanyProductService iCompanyProductService;
    @Autowired
    private ICooperateService iCooperateService;
    @Autowired
    private ICompanyMsgService iCompanyMsgService;

    /**
     * 提交企业入驻申请
     * @param companyApply
     * @return
     */
    @PostMapping("/commitCompanyApply")
    public R commitCompanyApply(@RequestBody CompanyApply companyApply){
        // 已申请或正在审核
        List<CompanyApply> apply = iCompanyApplyService.findCompanyApplyByMemberIdAndStatus(companyApply.getMemberId());
        if (apply.size() > 0 && apply.get(0).getIsShow() == 1) {
            return R.error("已申请或正在审核");
        } else if (apply.size() > 0 && apply.get(0).getIsShow() == 0){
            companyApply.setId(apply.get(0).getId());
            companyApply.setApplyDate(new Date());//设置申请时间
            companyApply.setStatus(0);//设置审核状态
            companyApply.setIsShow(1);
            iCompanyApplyService.updateCompanyApply(companyApply);
        } else {
            companyApply.setApplyDate(new Date());//设置申请时间
            companyApply.setStatus(0);//设置审核状态
            companyApply.setIsShow(1);
            iCompanyApplyService.insertCompanyApply(companyApply);
        }
        return R.ok();
    }

    @Autowired
    private IShopConfigService shopConfigService;
    /**
     * 获取开通会员信息
     * @param memberId
     * @return
     */
    @GetMapping("/getVipConfig")
    public R getVipConfig(@RequestParam String memberId){
        ShopConfig shopConfig = this.shopConfigService.findAll().get(0);
        HashMap<String, Object> map = new HashMap<>();
        map.put("vipPrice",shopConfig.getVipPrice());

        Member oldMember = this.memberService.selectMemberById(memberId);

        if(oldMember!=null){
            //判断用户会员是否过期
            if(oldMember.getIsVip().equals(MemberIsVip.YES.getValue())){
                if(DateUtils.getNowDate().getTime()>oldMember.getVipEndTime().getTime()){
                    Member update = new Member();
                    update.setIsVip(MemberIsVip.NO.getValue());
                    update.setId(oldMember.getId());
                    this.memberService.updateMember(update);
                    oldMember.setIsVip(MemberIsVip.NO.getValue());
                }
            }
        }else{
            oldMember = new Member();
            oldMember.setIsVip(MemberIsVip.NO.getValue());
        }
        //当前用户是否是vip
        map.put("isVip",oldMember.getIsVip());
        //会员特权图片
        map.put("vipPrivilegeImg",shopConfig.getVipPrivilegeImg());
        return RFactory.generateR(map);
    }

    /**
     * 购买钻石VIP
     * @param id 用户ID
     * @return
     */
    @PostMapping("/buyVip")
    public R buyVip(@RequestBody Member member) throws Exception{
        //验证参数
        if(member.getId() == null||member.getId().equals("")){
            return R.error("缺少用户ID");
        }
        if(member.getId().length() != 32){
            return R.error("参数错误");
        }
        //防止重复提交
        if(redisTemplate.opsForValue().increment("jquserbuyvip"+member.getId(),1) >1){
            return R.error("请勿重复提交");
        }
        redisTemplate.expire("jquserbuyvip"+member.getId(),10, TimeUnit.SECONDS);
        //根据用户ID查询用户信息
        Member memberById = memberService.selectMemberById(member.getId());
        if(memberById==null){
            return R.error("参数错误");
        }
        // 查询用户是否是会员
        if(memberById.getIsVip() == 1 || memberById.getIsJqVip() == 1) {
            return R.error("您已是VIP");
        }
        //生成待支付的充值记录
        JiaqinBuyvipRecord jiaqinBuyvipRecord = iJiaqinBuyvipRecordService.generate(member.getId(),new BigDecimal(200.00));
        System.out.println(jiaqinBuyvipRecord);
        //支付逻辑
        Map<String,String> payMap = PayUtil.yuZhiFu(jiaqinBuyvipRecord,"192.168.0.1",memberById.getOpenid());
        System.out.println("第二次签名结果:"+payMap);
        HashMap<String,Object> map = new HashMap<>();
        map.put("data",payMap);
        return R.ok(map);
    }

    @RequestMapping("/payresult")
    public void result(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception{
        //生成支付对象
        //System.out.println("--用户支付回调-------进入回调--------------------");
        WXPay wxPay = new WXPay(WxPayConfigRuImpl.getInstance());
        InputStream inputStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buff)) != -1) {
            outSteam.write(buff, 0, len);
        }
        inputStream.close();
        outSteam.close();
        String result = new String(outSteam.toByteArray(), "utf-8");

        String key = WxPayConfigRuImpl.getInstance().getKey();
        System.out.println(key);

        if (!WXPayUtil.isSignatureValid(result,key)) {
            System.out.println("回调签名验证失败！");
            return;
        }
        System.out.println("---用户支付回调------验证签名成功-----------------");
        Map<String, String> resultMap;
        //把微信传过来的xml数据转换为map
        resultMap = WXPayUtil.xmlToMap(result);
        System.out.println(resultMap);
        System.out.println("----用户支付回调-----开始处理订单-----------------");
        //查询充值记录 获取订单号
        String orderId = resultMap.get("out_trade_no");
        //根已支付订单ID处理用户会员 信息
        JiaqinBuyvipRecord jiaqinBuyvipRecord = iJiaqinBuyvipRecordService.selectJiaqinBuyvipRecordByRecordId(orderId);
        Member member = memberService.selectMemberById(jiaqinBuyvipRecord.getMemberId());
        if(memberService.payResult(jiaqinBuyvipRecord,member,resultMap.get("transaction_id"))>0){
            //处理成功通知微信
            String resStr = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            PrintWriter writer = response.getWriter();
            writer.write(resStr);
            writer.flush();
            writer.close();
            System.out.println("订单处理完成");
        }
        return;
    }

//
//    @Resource
//    private IPayLogService payLogService;
//    /**
//     * 会员支付
//     * @param memberId：用户ID
//     * @param contractId：合同ID
//     * @param req
//     * @return
//     */
//    @GetMapping("/buyVip")
//    public R buyVip(@RequestParam String memberId, String contractId, HttpServletRequest req){
//        // 查询用户是否存在
//        Member member = this.memberService.selectMemberById(memberId);
//        if(member == null) {
//            return R.error("用户不存在");
//        }
//        // 查询用户是否是会员
//        if(member.getIsVip() == 1 || member.getIsJqVip() == 1) {
//            return R.error("您已是VIP");
//        }
//
//        //获取会员价格
//        ShopConfig shopConfig = this.shopConfigService.findAll().get(0);
//
//        HashMap<String, Object> map = new HashMap<>();
//        //时间戳
//        map.put("timeStamp", DateUtils.getNowDate().getTime()+"");
//
//        //调用统一下单接口拿到prepay_id
//        SortedMap<String, Object> date = new TreeMap<String,Object>();
//
//        //返回用前端的date2
//        SortedMap<String, Object> date2 = new TreeMap<String,Object>();
//        date2.put("appId", AppBeanInjector.weixinConfig.getAppId());
//        date2.put("timeStamp",DateUtils.getNowDate().getTime());
//        date2.put("signType","MD5");
//
//        date.put("appid",AppBeanInjector.weixinConfig.getAppId());
//        date.put("attach","家禽会员支付");
//        date.put("openid",member.getOpenid());
//        date.put("body","家禽会员支付");
//        date.put("mch_id",AppBeanInjector.weixinConfig.getMch_id());
//        date.put("nonce_str",this.idGererateFactory.nextStringId());
//        date.put("notify_url",AppBeanInjector.weixinConfig.getContract_pay_url());
//        date.put("out_trade_no",member.getId()+"-"+this.idGererateFactory.nextStringId());
//        date.put("spbill_create_ip", StringUtils.getRemoteAddr(req));
//        float sessionmoney = Float.parseFloat(shopConfig.getVipPrice().toString());
//        String finalmoney = String.format("%.2f", sessionmoney);
//        finalmoney = finalmoney.replace(".", "");
//        String newStr = finalmoney.replaceFirst("^0*", "");
//        date.put("total_fee",newStr);
//        date.put("trade_type","JSAPI");
//        String perpayId = WeixinUtils.getPerpayId(date,date2);
//
//        date2.put("package",FBSStringUtil.format("prepay_id={0}",perpayId));
//
//        map.put("package",FBSStringUtil.format("prepay_id={0}",perpayId));
//        // paySign 签名
//        map.put("paySign",WeixinUtils.createSign(WeixinUtils.CHARSET,date2));
//        // 随机字符串
//        map.put("nonceStr",date2.get("nonceStr"));
//
//        // 生成支付记录
//        PayLog payLog = new PayLog();
//        payLog.setOutTradeNo((String) date.get("out_trade_no"));
//        payLog.setStatus(0);
//        payLog.setType(1);// 支付类型: 0-订单支付 1-会员支付 2-合同支付
//        payLog.setCreated(DateUtils.getNowDate());
//        payLog.setMemberId(memberId);
//        payLog.setResId(memberId);
//        payLog.setPrice(shopConfig.getVipPrice());
//        this.payLogService.insertPayLog(payLog);
//
//        return RFactory.generateR(map);
//    }
//
//
//    /**
//     * 微信回调方法
//     * @param req
//     * @param res
//     * @return
//     */
//    @PostMapping("/result")
//    public Object vipResult(HttpServletRequest req, HttpServletResponse res){
//        try {
//            InputStream inStream = req.getInputStream();
//            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
//            byte[] buffer = new byte[1024];
//            int len = 0;
//            while ((len = inStream.read(buffer)) != -1) {
//                outSteam.write(buffer, 0, len);
//            }
//            System.out.println("~~~~~~~~~~~~~~~~付款成功~~~~~~~~~");
//            outSteam.close();
//            inStream.close();
//            String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
//            Map<Object, Object> mapFromXml = WeixinUtils.doXMLParse(result);
//            SortedMap<String ,String > sortedMap = new TreeMap();
//            if (mapFromXml.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
//                PayLog payLog = this.payLogService.selectPayLogByNo(mapFromXml.get("out_trade_no").toString());
//                if(payLog.getStatus()==0){
//
//                    String memberId = mapFromXml.get("out_trade_no").toString().split("-")[0];
//                    Date date = new Date();
//                    Member member = this.memberService.selectMemberById(memberId);
//                    if (member == null) {
//                        sortedMap.put("return_code","FAIL");
//                        sortedMap.put("return_msg","签名失败");
//                        res.reset();
//                        res.getWriter().write(parseXML(sortedMap));
//                    }
//                    //  验签成功后
//                    //会员信息 开通会员
//                    Member update = new Member();
//                    GregorianCalendar gregorianCalendar = new GregorianCalendar();
//                    update.setId(memberId);
//                    update.setIsVip(1);
//                    update.setIsJqVip(1);
//                    // 续费一年
//                    gregorianCalendar.setTime(DateUtils.getNowDate());
//                    gregorianCalendar.add(Calendar.YEAR,1);
//                    update.setVipEndTime(gregorianCalendar.getTime());
//                    this.memberService.updateMember(update);
//
//                    // 更新支付记录
//                    PayLog updatePayLog = new PayLog();
//                    updatePayLog.setId(payLog.getId());
//                    updatePayLog.setStatus(1);
//                    this.payLogService.updatePayLog(updatePayLog);
//
//                }
//                sortedMap.put("return_code","SUCCESS");
//                sortedMap.put("return_msg","OK");
//                BufferedOutputStream out = new BufferedOutputStream(
//                        res.getOutputStream());
//                out.write(parseXML(sortedMap).getBytes());
//                out.flush();
//                out.close();
//
//            }else {
//                sortedMap.put("return_code","FAIL");
//                sortedMap.put("return_msg","签名失败");
//                BufferedOutputStream out = new BufferedOutputStream(
//                        res.getOutputStream());
//                out.write(parseXML(sortedMap).getBytes());
//                out.flush();
//                out.close();
//            }
//            return "success";
//        } catch (Exception e) {
//            return "failure";
//        }
//    }
//
//
//    //输出XML
//    public String parseXML(Map map) {
//        StringBuffer sb = new StringBuffer();
//        sb.append("<xml>\n");
//        Set es = map.entrySet();
//        Iterator it = es.iterator();
//        while(it.hasNext()) {
//            Map.Entry entry = (Map.Entry)it.next();
//            String k = (String)entry.getKey();
//            String v = (String)entry.getValue();
//            if(null != v && !"".equals(v) && !"appkey".equals(k)) {
//
//                sb.append("<" + k +"><![CDATA[" + v + "]]></" + k + ">\n");
//            }
//        }
//        sb.append("</xml>");
//        return sb.toString();
//    }

    /**
     *  关注用户
     * @param memberId      用户
     * @param toMemberId    被关注用户
     * @return
     */
    @GetMapping("/followMember")
    public R followMember(String memberId,String toMemberId){
        if(memberId == null || memberId.equals("")|| memberId.length() != 32){
            return R.error("参数错误");
        }
        if(toMemberId == null || toMemberId.equals("")|| toMemberId.length() != 32){
            return R.error("参数错误");
        }
        if(memberId.equals(toMemberId)){
            return R.error("无法关注自己");
        }
        //查是否已关注
        JiaqinFollowMember jiaqinFollowMemberIs = iJiaqinFollowMemberService.selectJiaqinFollowMemberByMemberIdAndToMemberId(memberId,toMemberId);
        if(jiaqinFollowMemberIs != null ){
            return R.error("已关注此用户");
        }
        // 添加我的粉丝数字提示
        NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(toMemberId);
        if (numberTips != null) {
            NumberTips tips = new NumberTips();
            tips.setId(numberTips.getId());
            tips.setFansNum(1);
            numberTipsService.updateNumberTips(tips);
        }
        JiaqinFollowMember jiaqinFollowMember = new JiaqinFollowMember();
        jiaqinFollowMember.setMemberId(memberId);//设置用户ID
        jiaqinFollowMember.setFollowMemberId(toMemberId);//设置被关注用户ID
        jiaqinFollowMember.setFollowAt(new Date());
        return  iJiaqinFollowMemberService.insertJiaqinFollowMember(jiaqinFollowMember)>0?R.ok("关注成功"):R.error("关注失败");
    }

    @Autowired
    private IJiaqinFollowCompanyService jiaqinFollowCompanyService;
    /**
     *  取消关注用户
     * @param memberId      用户
     * @param toMemberId    被关注用户
     * @return
     */
    @GetMapping("/unFollowMember")
    public R unFollowMember(String memberId,String toMemberId){
        if(memberId == null || memberId.equals("")|| memberId.length() != 32){
            return R.error("参数错误");
        }
        if(toMemberId == null || toMemberId.equals("")|| toMemberId.length() != 32){
            return R.error("参数错误");
        }
        JiaqinFollowMember jiaqinFollowMember = iJiaqinFollowMemberService.selectJiaqinFollowMemberByMemberIdAndToMemberId(memberId,toMemberId);
        if(jiaqinFollowMember == null){
            return R.error("参数错误,关系不存在");
        }
        // 删除关注企业表里的关注
        Company company = companyService.selectCompanyByMemberId(toMemberId);
        if (company != null) {
            JiaqinFollowCompany jiaqinFollowCompany = new JiaqinFollowCompany();
            jiaqinFollowCompany.setMemberId(memberId);
            jiaqinFollowCompany.setFollowCompanyId(company.getId());
            // followMember.setType(1);
            List<JiaqinFollowCompany> jiaqinFollowCompanyList = jiaqinFollowCompanyService.selectJiaqinFollowCompanyList(jiaqinFollowCompany);
            if (jiaqinFollowCompanyList.size() > 0) {
                for (JiaqinFollowCompany JFC : jiaqinFollowCompanyList) {
                    jiaqinFollowMemberService.deleteJiaqinFollowMemberById(JFC.getId());
                }
            }
        }
        return  iJiaqinFollowMemberService.deleteJiaqinFollowMemberById(jiaqinFollowMember.getId())>0?R.ok("取消关注成功"):R.error("取消关注失败");
    }

    /**
     * 根据用户ID获取用户关注列表
     * @param memberId
     * @return
     */
    @GetMapping("/getFollowMembers")
    public R getFollowMembers(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize,String memberId){
        if(memberId == null || memberId.equals("")|| memberId.length() != 32){
            return R.error("参数错误");
        }
        PageInfo<JiaqinFollowMember> pageInfo = iJiaqinFollowMemberService.selectJiaqinFollowMemberByMemberId(pageNum,pageSize,memberId);
        HashMap<String,Object> map = new HashMap<>();
        map.put("data",pageInfo);
        return R.ok(map);
    }

    @Autowired
    private ICompanyService companyService;
    @Autowired
    private IJiaqinFollowMemberService jiaqinFollowMemberService;
    /**
     *  关注企业
     * @param memberId      用户
     * @param toMemberId    被关注企业
     * @return
     */
    @GetMapping("/followCompany")
    public R followCompany(String memberId,String toCompanyId){
        if(memberId == null || memberId.equals("")|| memberId.length() != 32){
            return R.error("参数错误");
        }
        if(toCompanyId == null || toCompanyId.equals("")|| toCompanyId.length() != 32){
            return R.error("参数错误");
        }
        //查是否已关注
        JiaqinFollowCompany jiaqinFollowCompanyIs = iJiaqinFollowCompanyService.selectJiaqinFollowMemberByMemberIdAndToCompanyId(memberId,toCompanyId);
        if(jiaqinFollowCompanyIs != null ){
            return R.error("已关注此企业");
        }
        // 插入关注用户表
        Company company = companyService.selectCompanyById(toCompanyId);
        if (company != null) {
            JiaqinFollowMember followMember = jiaqinFollowMemberService.selectJiaqinFollowMemberByMemberIdAndToMemberId(memberId, company.getMemberId());
            JiaqinFollowMember jiaqinFollowMember = new JiaqinFollowMember();
            // 插入关注用户表
            if (followMember == null) {
                Member memberById = memberService.selectMemberById(company.getMemberId());
                if (memberById != null) {
                    jiaqinFollowMember.setMemberId(memberId);
                    jiaqinFollowMember.setFollowMemberId(memberById.getId());
                    jiaqinFollowMember.setFollowAt(new Date());
                    jiaqinFollowMember.setType(1);
                    jiaqinFollowMemberService.insertJiaqinFollowMember(jiaqinFollowMember);
                }
            } else {// 改变关注用户表 被关注用户身份：0-个人 1-企业
                followMember.setId(followMember.getId());
                jiaqinFollowMember.setType(1);
                jiaqinFollowMemberService.updateJiaqinFollowMember(jiaqinFollowMember);
            }
            // 添加我的粉丝数字提示
            NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(company.getMemberId());
            if (numberTips != null) {
                NumberTips tips = new NumberTips();
                tips.setId(numberTips.getId());
                tips.setFansNum(1);
                numberTipsService.updateNumberTips(tips);
            }
        }
        JiaqinFollowCompany jiaqinFollowCompany = new JiaqinFollowCompany();
        jiaqinFollowCompany.setMemberId(memberId);//设置用户ID
        jiaqinFollowCompany.setFollowCompanyId(toCompanyId);//设置被关注企业ID
        jiaqinFollowCompany.setFollowAt(new Date());
        return  iJiaqinFollowCompanyService.insertJiaqinFollowCompany(jiaqinFollowCompany)>0?R.ok("关注成功"):R.error("关注失败");
    }


    /**
     *  取消关注企业
     * @param memberId      企业
     * @param toMemberId    被关注企业
     * @return
     */
    @GetMapping("/unFollowCompany")
    public R unFollowCompany(String memberId,String toCompanyId){
        if(memberId == null || memberId.equals("")|| memberId.length() != 32){
            return R.error("参数错误");
        }
        if(toCompanyId == null ||toCompanyId.equals("")||toCompanyId.length() != 32){
            return R.error("参数错误");
        }
        JiaqinFollowCompany jiaqinFollowCompany = iJiaqinFollowCompanyService.selectJiaqinFollowMemberByMemberIdAndToCompanyId(memberId,toCompanyId);
        if(jiaqinFollowCompany == null){
            return R.error("参数错误,关系不存在");
        }
        // 删除关注用户表里的关注
        Company company = companyService.selectCompanyById(toCompanyId);
        JiaqinFollowMember followMember = new JiaqinFollowMember();
        followMember.setMemberId(memberId);
        followMember.setFollowMemberId(company.getMemberId());
        // followMember.setType(1);
        List<JiaqinFollowMember> followMemberList = jiaqinFollowMemberService.selectJiaqinFollowMemberList(followMember);
        if (followMemberList.size() > 0) {
            for (JiaqinFollowMember JFM : followMemberList) {
                jiaqinFollowMemberService.deleteJiaqinFollowMemberById(JFM.getId());
            }
        }
        return  iJiaqinFollowCompanyService.deleteJiaqinFollowCompanyById(jiaqinFollowCompany.getId())>0?R.ok("取消关注成功"):R.error("取消关注失败");
    }

    /**
     * 根据用户ID获取企业关注列表
     * @param memberId
     * @return
     */
    @GetMapping("/getFollowCompanys")
    public R getFollowCompanys(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize,String memberId){
        if(memberId == null || memberId.equals("")|| memberId.length() != 32){
            return R.error("参数错误");
        }
        PageInfo<JiaqinFollowCompany> pageInfo = iJiaqinFollowCompanyService.selectJiaqinFollowCompanyByMemberId(pageNum,pageSize,memberId);
        HashMap<String,Object> map = new HashMap<>();
        map.put("data",pageInfo);
        return R.ok(map);
    }

    /**
     *  收藏供应
     * @param memberId      用户
     * @param toMemberId    被收藏的供应
     * @return
     */
    @GetMapping("/collectSupply")
    public R collectSupply(String memberId,String toSupplyId){
        if(memberId == null || memberId.equals("")|| memberId.length() != 32){
            return R.error("参数错误");
        }
        if(toSupplyId == null || toSupplyId.equals("")|| toSupplyId.length() != 32){
            return R.error("参数错误");
        }
        //查是否已关注
        JiaqinSupplyCollect jiaqinSupplyCollectIs = iJiaqinSupplyCollectService.selectJiaqinSupplyCollectByMemberIdAndToSupplyId(memberId,toSupplyId);
        if(jiaqinSupplyCollectIs != null ){
            return R.error("已收藏此供应");
        }
        JiaqinSupplyCollect jiaqinSupplyCollect = new JiaqinSupplyCollect();
        jiaqinSupplyCollect.setMemberId(memberId);
        jiaqinSupplyCollect.setSupplyId(toSupplyId);
        jiaqinSupplyCollect.setCollectAt(new Date());
        return iJiaqinSupplyCollectService.insertJiaqinSupplyCollect(jiaqinSupplyCollect)>0?R.ok("收藏成功"):R.error("收藏失败");
    }

    /**
     *  1
     * @param memberId      用户ID
     * @param toMemberId   被收藏供应ID
     * @return
     */
    @GetMapping("/unCollectSupply")
    public R unCollectSupply(String memberId,String toSupplyId){
        if(memberId == null || memberId.equals("")|| memberId.length() != 32){
            return R.error("参数错误");
        }
        if(toSupplyId == null ||toSupplyId.equals("")||toSupplyId.length() != 32){
            return R.error("参数错误");
        }
        JiaqinSupplyCollect jiaqinSupplyCollect = iJiaqinSupplyCollectService.selectJiaqinSupplyCollectByMemberIdAndToSupplyId(memberId,toSupplyId);
        if(jiaqinSupplyCollect == null){
            return R.error("参数错误,关系不存在");
        }
        return iJiaqinSupplyCollectService.deleteJiaqinSupplyCollectById(jiaqinSupplyCollect.getId())>0?R.ok("取消收藏成功"):R.error("取消收藏失败");
    }

    /**
     * 根据用户ID获取供应收藏列表
     * @param memberId
     * @return
     */
    @GetMapping("/getCollectSupplys")
    public R getCollectSupplys(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize,String memberId){
        if(memberId == null || memberId.equals("")|| memberId.length() != 32){
            return R.error("参数错误");
        }
        PageInfo<JiaqinSupplyCollect> pageInfo = iJiaqinSupplyCollectService.selectJiaqinSupplyCollectByMemberId(pageNum,pageSize,memberId);
        HashMap<String,Object> map = new HashMap<>();
        map.put("data",pageInfo);
        return R.ok(map);
    }

    /**
     * 意向留言
     * @param memberId
     * @param message
     * @return
     */
    @GetMapping("/intentionMessage")
    public R intentionMessage(String memberId,String message){
        Member memberById = memberService.selectMemberById(memberId);
        IntentionMessage intentionMessage = new IntentionMessage();
        intentionMessage.setCreateAt(new Date());
        intentionMessage.setMemberid(memberId);
        intentionMessage.setContent(message);
        intentionMessage.setMemberName(memberById.getUsername());
        return intentionMessageService.insertIntentionMessage(intentionMessage)>0?R.ok("留言成功"):R.error("留言失败");
    }

    /**
     * 修改头像
     * @return
     */
    @GetMapping("/updateAvatar")
    public R updateAvatar(String memberId,String avatar){
        Member member = new Member();
        member.setId(memberId);
        member.setHeadpic(avatar);
        return memberService.updateMember(member)>0?R.ok("修改成功!"):R.error("修改失败!");
    }

    /**
     * 获取企业名片列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getCompanys")
    public R getCompanys(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize,String userId,Company company){
        HashMap<String,Object> map = new HashMap<>();
        PageInfo<Company> pageInfo = iCompanyService.selectCompanyListPage(pageNum,pageSize,userId,company);
        map.put("data",pageInfo);
        return R.ok(map);
    }

    /**
     * 获取招聘行业列表
     * @return
     */
    @GetMapping("/getRecruitIndustry")
    public R getRecruitIndustry(){
        HashMap<String,Object> map = new HashMap<>();
        List<RecruitIndustry> list = iRecruitIndustryService.selectRecruitIndustryList(new RecruitIndustry());
        map.put("data",list);
        return R.ok(map);
    }

    /**
     * 根据用户ID查询企业信息
     * @param memberId
     * @return
     */
    @GetMapping("/getCompanyByMemberId")
    public R getCompanyByMemberId(String memberId){
        if(memberId == null||memberId.equals("")){
            return R.error("参数错误");
        }
        HashMap<String,Object> map = new HashMap<>();
        Company company = iCompanyService.selectCompanyByMemberId(memberId);
        map.put("data",company);
        return R.ok(map);
    }

    /**
     * 获取企业行业
     * @return
     */
    @GetMapping("/getComapanyIndustry")
    public R getCompanyIndustry(){
        HashMap<String,Object> map = new HashMap<>();
        List<CompanyIndustry> list = iCompanyIndustryService.selectCompanyIndustryList(new CompanyIndustry());
        map.put("list",list);
        return R.ok(map);
    }

    /**
     * 根据企业ID查询企业简单信息
     * @param memberId
     * @return
     */
    @GetMapping("/getSimpleCompanyById")
    public R getCompanyId(String companyId){
        if(companyId == null||companyId.equals("")){
            return R.error("参数错误");
        }
        HashMap<String,Object> map = new HashMap<>();
        // Company company = iCompanyService.selectCompanyById(companyId);
        Company company = companyService.selectCompanyByMemberId(companyId);
        Member member = memberService.selectMemberById(company.getMemberId());
        if (member != null) {
            company.setWechat(member.getWechat());
        }
        map.put("data",company);
        return R.ok(map);
    }
    /**
     * 根据企业ID查询企业复杂信息
     * @param memberId
     * @return
     */
    @GetMapping("/getAllCompanyById")
    public R getAllCompanyId(String companyId){
        if(companyId == null||companyId.equals("")){
            return R.error("参数错误");
        }
        HashMap<String,Object> map = new HashMap<>();
        Company company = companyService.selectCompanyByMemberId(companyId);
        if (company != null) {
            JSONObject jsonObject = iCompanyService.selectCompanyDetail(company.getId());
            map.put("data",jsonObject);
        } else {
            Member memberById = memberService.selectMemberById(companyId);
            map.put("data",memberById);
        }
        return R.ok(map);
    }

    /**
     * 根据企业ID查询企业产品列表
     * @param memberId
     * @return
     */
    @GetMapping("/getProductListByCompanyId")
    public R getProductListByCompanyId(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize,String companyId){
        if(companyId == null||companyId.equals("")){
            return R.error("参数错误");
        }
        HashMap<String,Object> map = new HashMap<>();
        CompanyProduct companyProduct = new CompanyProduct();
        companyProduct.setCompanyId(companyId);
        PageHelper.startPage(pageNum,pageSize);
        List<CompanyProduct> list = iCompanyProductService.selectCompanyProductListInfo(companyProduct);
        PageInfo<CompanyProduct> pageInfo = new PageInfo<>(list);
        map.put("data",pageInfo);
        return R.ok(map);
    }

    /**
     * 根据产品ID查询企业产品详情
     * @param memberId
     * @return
     */
    @GetMapping("/getProductDetail")
    public R getProductDetail(String productId){
        if(productId == null||productId.equals("")){
            return R.error("参数错误");
        }
        HashMap<String,Object> map = new HashMap<>();
        CompanyProduct companyProduct = iCompanyProductService.selectCompanyProductById(productId);
        map.put("data",companyProduct);
        return R.ok(map);
    }

    /**
     * 根据企业ID查询企业是否vip
     * @param memberId
     * @return
     */
    @GetMapping("/companyIsVip")
    public R getIsVipCompanyId(String companyId){
        if(companyId == null||companyId.equals("")){
            return R.error("参数错误");
        }
        HashMap<String,Object> map = new HashMap<>();
        Company company = iCompanyService.selectCompanyById(companyId);
        if (company == null) {
            return R.error("无");
        }
        Member member = memberService.selectMemberById(company.getMemberId());
        map.put("data",member.getIsJqVip());
        return R.ok(map);
    }

    /**
     * 关注货品分类
     * @param memberQuoteClass
     * @return
     */
    @PostMapping("/addMemberQuotationClass")
    public R addMemberQuotationClass(@RequestBody MemberQuoteClass memberQuoteClass){
        return iMemberQuoteClassService.insertMemberQuoteClass(memberQuoteClass)>0?R.ok("关注成功"):R.error("关注失败");
    }

    /**
     * 取消关注货品分类
     * @param memberQuoteClass
     * @return
     */
    @GetMapping("/delMemberQuotationClass")
    public R addMemberQuotationClass(String memberId,String quotatonClassId){
        return iMemberQuoteClassService.deleteMemberQuoteClassById(memberId,quotatonClassId)>0?R.ok("取消关注成功"):R.error("取消关注失败");
    }

    /**
     * 获取我的关注
     * @param
     * @returncommitCompanyApply
     */
    @GetMapping("/getMemberQuotationClass")
    public R getMemberQuotationClass(MemberQuoteClass memberQuoteClass){
        HashMap<String,Object> map = new HashMap<>();
        List<MemberQuoteClass> list = iMemberQuoteClassService.selectMemberQuoteClassList(memberQuoteClass);
        map.put("data",list);
        return R.ok(map);
    }


    /**
     * 获取合作信息
     * @return
     */
    @GetMapping("/getCooperate")
    public R getCooperate(){
        HashMap<String,Object> map = new HashMap<>();
        Cooperate cooperate = iCooperateService.selectCooperateById("b42b2550c00b44ad9954527a153b3061");
        map.put("data",cooperate);
        return R.ok(map);
    }

    @Autowired
    private ICooperateMsgService iCooperateMsgService;
    /**
     * 提交合作信息
     * @param msg
     * @param memberId
     * @return
     */
    @GetMapping("/cooperateMsg")
    public R cooperateMsg(String msg,String memberId){
        CooperateMsg cooperateMsg = new CooperateMsg();
        cooperateMsg.setContent(msg);
        cooperateMsg.setMemberId(memberId);
        cooperateMsg.setCreateDate(new Date());
        iCooperateMsgService.insertCooperateMsg(cooperateMsg);
        return R.ok("提交成功");
    }

    /**
     * 提交企业留言
     * @param msg
     * @param memberId
     * @return
     */
    @GetMapping("/companyMsg")
    public R cooperateMsg(String msg,String memberId,String companyId){
        CompanyMsg companyMsg = new CompanyMsg();
        companyMsg.setCompanyId(companyId);
        companyMsg.setContent(msg);
        companyMsg.setCreateDate(new Date());
        companyMsg.setMemberId(memberId);
        companyMsg.setId(UUID.randomUUID().toString().replace("-",""));
        iCompanyMsgService.insertCompanyMsg(companyMsg);
        return R.ok("提交成功");
    }

    @Autowired
    private INumberTipsService numberTipsService;
    /**
     * 根据用户ID查我的粉丝列表
     * @param memberId
     * @return
     */
    @GetMapping("/getMyFans")
    public R getMyFans(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum,
                       @RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
                       String memberId) {
        if(memberId == null || memberId.equals("")) {
            return R.error("参数错误");
        }
        // PageInfo<JiaqinFollowCompany> pageInfo = iJiaqinFollowCompanyService.selectJiaqinFollowCompanyByMemberId(pageNum,pageSize,memberId);
        // HashMap<String,Object> map = new HashMap<>();
        // map.put("data",pageInfo);
        // return R.ok(map);
        // 取消我的粉丝数字提示
        NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(memberId);
        if (numberTips != null) {
            NumberTips tips = new NumberTips();
            tips.setId(numberTips.getId());
            tips.setFansNum(0);
            numberTipsService.updateNumberTips(tips);
        }
        PageInfo<JiaqinFollowMember> pageInfo = iJiaqinFollowMemberService.getMyFans(pageNum,pageSize,memberId);
        HashMap<String,Object> map = new HashMap<>();
        map.put("data",pageInfo);
        return R.ok(map);
    }

}
